package org.xnsg.app.controller;

import com.eova.common.utils.EncryptUtil;
import com.eova.model.Button;
import com.eova.model.EovaLog;
import com.eova.model.Menu;
import com.eova.model.User;
import com.eova.service.sm;
import com.eova.widget.WidgetUtil;
import com.jfinal.core.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xnsg.app.core.HttpCode;
import org.xnsg.app.core.bean.Result;
import org.xnsg.app.core.helper.LoginHelper;

import java.util.*;

/**
 * @author zhaopan
 * @date :2017/4/16
 * @Description:登录相关的控制类 重写原始的IndexController的类方法
 */
public class LoginController extends Controller
{
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);


    public void doLogin()
    {
        String method = "doLogin";
        //String prompt = this.className + "." + method + ">";
        //logger.info(prompt + "start ...");
        String loginId = this.getPara("loginId");
        String loginPwd = this.getPara("loginPwd");
        User user = User.dao.getByLoginId(loginId);
        //int i=user.getInt("id");
        Map resultMap = new HashMap();
        if (user == null)
        {
            resultMap.put("msg", "用户名不存在");
            resultMap.put("httpCode", HttpCode.MULTI_STATUS);
            resultMap.put("success", false);
            this.renderJson(new Result(resultMap));
        } else if (!user.getStr("login_pwd").equals(EncryptUtil.getSM32(loginPwd)))
        {
            //this.setAttr("msg", "密码错误");
            //this.keepPara(new String[]{"loginId"});
            resultMap.put("msg", "密码错误");
            resultMap.put("httpCode", HttpCode.LOGIN_FAIL);
            resultMap.put("success", false);
            this.renderJson(new Result(resultMap));
        } else
        {
            String uname = user.getStr("login_id");
            logger.info(" 登录成功! uname = [" + uname + "]");
            this.setSessionAttr("user", user);
            //System.out.println(prompt + "end.");
            //this.redirect("/");
            //logger.info("加载菜单start......");
            //LoginHelper.getMenuList(resultMap, user);//加载根菜单
            EovaLog.dao.info(this, 1, "system_login[" + uname + "]");
            //resultMap.put("data", rootList);//返回根菜单
            resultMap.put("httpCode", HttpCode.OK);
            resultMap.put("msg", uname + "登录成功");
            resultMap.put("success", true);
            //String menuJson=showTree(3);
            //System.out.println(user);

            resultMap.put("user", user.toJson());
            Map<String, Object> data = showTree(3, user);
            resultMap.put("menus", data);
            //resultMap.put("btnList", btnList(data,user));

//            String result=JsonKit.toJson(new Result(resultMap));
//            Gson gson = new Gson();
//            Map<String, Object> map = gson.fromJson(result, Map);
//            System.out.println(map.get("result"));
//            if(resultMap.get("data")!=null&&!"".equals(resultMap.get("data"))){
//
//            }

            this.renderJson(new Result(resultMap));

        }
    }


    public Map showTree(Integer rootId, User user)
    {
        //Integer rootId = this.getParaToInt(0);
        if (rootId == null || user == null)
        {
            return null;
        } else
        {
            //User user = (User) this.getSessionAttr("user");
            int rid = user.getInt("rid").intValue();
            Map allMenu = sm.auth.getByParentId(rootId.intValue());
            WidgetUtil.formatEasyTree(allMenu);
            List authMenuCodeList = sm.auth.queryMenuCodeByRid(rid);
            LinkedHashMap authMenu = new LinkedHashMap();
            LinkedHashMap resultMap = new LinkedHashMap();
            Iterator json = allMenu.entrySet().iterator();
            //List resultList = new ArrayList();
            while (json.hasNext())
            {
                Map.Entry authParent = (Map.Entry) json.next();
                Menu menu = (Menu) authParent.getValue();
                if (authMenuCodeList.contains(menu.getStr("code")) && LoginHelper.alowMenus.contains(menu.getStr("code")))
                {
                    authMenu.put((Integer) authParent.getKey(), menu);
                }
            }
            Iterator<Map.Entry<String, Menu>> it = authMenu.<String, Menu>entrySet().iterator();
            while (it.hasNext())
            {
                Map.Entry<String, Menu> entry = it.<String, Menu>next();
                resultMap.put(entry.getValue().getStr("code"), entry.getValue().getStr("text"));
                List<Button> btnList = Button.dao.queryByMenuCode(entry.getValue().getStr("code"), user.getInt("rid").intValue());
                List<String> btnNames = new ArrayList<String>();
                for (Button btn : btnList)
                {
                    String name = btn.getStr("name");
                    btnNames.add(name);
                }

                resultMap.put(entry.getValue().getStr("code"), btnNames);
            }
            //resultList.add(resultMap);
            List<Button> btnList = Button.dao.queryByMenuCode("m_pt_user_mgr", user.getInt("rid").intValue());
            for (Button btn : btnList)
            {
                if ("新增".equals(btn.getStr("name")))
                {
                    resultMap.put("m_user_add", new ArrayList<String>());
                    break;
                }
            }
            return resultMap;
/*
            LinkedHashMap authParent1 = new LinkedHashMap();
            Iterator var10 = authMenu.entrySet().iterator();
            //找出二级菜单
            while (var10.hasNext())
            {
                Map.Entry json1 = (Map.Entry) var10.next();
                WidgetUtil.getParent(allMenu, authParent1, (Menu) json1.getValue());
            }

            authParent1.remove(rootId);
            //
            authParent1.putAll(authMenu);
            Iterator var11 = authParent1.entrySet().iterator();
            while (var11.hasNext())
            {
                Map.Entry json1 = (Map.Entry) var11.next();
                if (!LoginHelper.alowMenus.contains(((Menu) json1.getValue()).get("code")))
                {
                    var11.remove();
                }
            }
            String json2 = WidgetUtil.menu2TreeJson(authParent1, rootId);
            */
            // return null;
        }

    }

    public Map btnList(Map<String, String> data, User user)
    {
        Map resultMap = new HashMap();
        //User user = User.dao.getByLoginId(getPara("userId"));
        // this.setSessionAttr("user", user);
        for (Map.Entry<String, String> entry : data.entrySet())
        {
            Menu menu = Menu.dao.findByCode(entry.getKey());
            if (menu != null)
            {
                List<Button> btnList = Button.dao.queryByMenuCode(entry.getKey(), user.getInt("rid").intValue());
                List<String> btnNames = new ArrayList<String>();
                for (Button btn : btnList)
                {
                    String name = btn.getStr("name");
                    btnNames.add(name);
                }

                resultMap.put(entry.getKey(), btnNames);
            }

        }
        return resultMap;
    }

}
